package com.hoyin.viewtest.dependencies;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.hoyin.viewtest.R;

import java.util.List;

public class ImageListAdapter extends ArrayAdapter<ListItem> {
	private int resourceId;
	private final String TAG = "ImageListAdapter";
	public ImageListAdapter(Context context, int textViewResourceId, List<ListItem> objects) {
		super(context, textViewResourceId, objects);
		this.resourceId = textViewResourceId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		/**
		 * getView()方法在每个子项被滚动到屏幕内的时候被调用
		 * 此处作为一个回调函数对每个item的显示效果做适配之后返回对应的view
		 */
		ListItem item = getItem(position);
		View view;
		ViewHolder viewHolder;
		if (convertView == null) {
			view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
			/**
			 * 使用内部类ViewHolder，将ListItem中的控件进行缓存
			 */
			viewHolder = new ViewHolder();
			viewHolder.itemImage = view.findViewById(R.id.list_item_image_view);
			viewHolder.itemText = view.findViewById(R.id.list_item_text_view);
			view.setTag(viewHolder);//将viewHolder存储在View中
		} else {
			view = convertView;
			viewHolder = (ViewHolder) view.getTag();
		}
		viewHolder.itemImage.setImageResource(item.getImageId());
		viewHolder.itemText.setText(item.getName());
		return view;
	}

	public class ViewHolder {
		ImageView itemImage;
		TextView itemText;
	}
}
